package org.dromara.web.service;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.article.domain.vo.BehaviorQueryVo;
import org.dromara.article.domain.vo.BehaviorVo;
import org.dromara.article.domain.vo.UserDetailQueryVo;
import org.dromara.article.domain.vo.UserDetailVo;
import org.dromara.article.mapper.ArticleMapper;
import org.dromara.common.core.domain.R;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.web.domain.vo.OverviewVo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
public class StatService {


    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private ArticleMapper articleMapper;


    /**
     * 获取概览数据
     *
     * @return
     */
    public OverviewVo getOverviewData() {
        OverviewVo vo = new OverviewVo();
        vo.setTotalUsers(sysUserMapper.countUser());
        vo.setTotalArticles(articleMapper.selectCount(null));
        return vo;
    }

    /**
     * 查询用户行为数据
     *
     * @param queryVo
     * @return
     */
    public R<BehaviorVo> behavior(BehaviorQueryVo queryVo) {
        // 查询总领取数量
        BehaviorVo behaviorVo = new BehaviorVo();
        // 查询总领取数量
        Long claimedCount = articleMapper.selectClaimedCount(queryVo.getStartTime(), queryVo.getEndTime());
        // 查询总发布数量
        Long publishedCount = articleMapper.selectPublishedCount(queryVo.getStartTime(), queryVo.getEndTime());
        // 查询总废弃数量
        Long disCount = articleMapper.selectDisCount(queryVo.getStartTime(), queryVo.getEndTime());
        // 查询总活跃用户数
        Long activeUserCount = articleMapper.selectActiveUserCount(queryVo.getStartTime(), queryVo.getEndTime());

        behaviorVo.setTotalClaimed(claimedCount);
        behaviorVo.setTotalPublished(publishedCount);
        behaviorVo.setTotalDiscarded(disCount);
        behaviorVo.setActiveUsers(activeUserCount);
        if (publishedCount == 0) {
            behaviorVo.setPublishRate(BigDecimal.ZERO);
        } else {
            behaviorVo.setPublishRate(NumberUtil.round((double) publishedCount / claimedCount, 2));

        }
        return R.ok(behaviorVo);
    }

    /**
     * 查询用户发文数据详情
     *
     * @param userDetailQueryVo
     * @param pageQuery
     * @return
     */
    public List<UserDetailVo> userDetail(UserDetailQueryVo userDetailQueryVo, PageQuery pageQuery) {
        IPage<UserDetailVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        List<UserDetailVo> list = articleMapper.selectUserDetailList(userDetailQueryVo, page);
        return list;
    }
}
